<?php

namespace app\api\controller;

use app\common\controller\ApiBase;
use app\common\model\Category;
use app\common\model\UserAttribute;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;

class Hobby extends ApiBase
{
    protected $noNeedLogin = ['list'];
    protected $noNeedRight = ['*'];

    /**
     * 兴趣爱好列表
     * @return void
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function list()
    {
        $where = [
            'type'   => 'hobby',
            'status' => 'normal'
        ];

        $hobby = Category::where($where)
            ->field(['id', 'name', 'type', 'flag'])
            ->paginate($this->getPaginate());

        $data = $hobby->items();
        $count = $hobby->total();

        $this->success('成功', ['list' => $data, 'count' => $count]);
    }

    /**
     * 我的兴趣爱好
     * @return void
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function myHobby()
    {
        $userAttribute = UserAttribute::where(['user_id' => $this->auth->id])->find();
        $data = empty($userAttribute['category_ids']) ? [] : explode(',', $userAttribute['category_ids']);
        $this->success('成功', ['select' => $data]);
    }

    /**
     * 设置我的爱好
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function setHobby()
    {
        $this->checkRequestParam(\app\common\validate\Hobby::class);
        $params = $this->request->param();
        $ids = $params['ids'];
        $userId = $this->auth->id;
        $data = [
            'category_ids' => $ids,
            'createtime' => time()
        ];

        $result = false;
        $userAttribute = UserAttribute::where(['user_id' => $userId])->find();
        if (empty($userAttribute)) {
            $data['user_id'] = $userId;
            $result = UserAttribute::create($data);
        } else {

            $user = new UserAttribute();
            $result = $user->save($data, ['user_id' => $userId]);
        }


        if (empty($result)) {
            $this->error('设置失败');
        }
        $this->success('设置成功');
    }
}
